package main

import (
	"github.com/aberic/gnomon/grope"
	"github.com/aberic/gnomon/log"
	"github.com/aberic/proc"
	"github.com/aberic/proc/protos"
	"google.golang.org/grpc"
	proto "gykjgit.dccnet.com.cn/chain/proto/swarm"
	"gykjgit.dccnet.com.cn/chain/swarm/comm"
	"gykjgit.dccnet.com.cn/chain/swarm/router"
	gRPC "gykjgit.dccnet.com.cn/chain/swarm/rpc"
	jRPC "gykjgit.dccnet.com.cn/chain/swarm/rpcjson"
	"gykjgit.dccnet.com.cn/chain/swarm/service"
	"net"
	"net/rpc"
	"net/rpc/jsonrpc"
)

// volume /home/data/log
// volume /home/data/platform

func gRPCListener() {
	var (
		listener net.Listener
		err      error
	)
	if listener, err = net.Listen("tcp", ":20219"); nil != err {
		panic(err)
	}
	server := grpc.NewServer()
	proto.RegisterResourceServerServer(server, &gRPC.ResourceServer{})
	proto.RegisterStackServerServer(server, &gRPC.StackServer{})
	proto.RegisterProjectServerServer(server, &gRPC.ProjectServer{})
	proto.RegisterProcServerServer(server, &gRPC.ProcServer{})
	proto.RegisterContainerServerServer(server, &gRPC.ContainerServer{})
	proto.RegisterImageServerServer(server, &gRPC.ImageServer{})
	proto.RegisterServiceServerServer(server, &gRPC.ServiceServer{})
	proto.RegisterDirServerServer(server, &gRPC.DirServer{})
	proto.RegisterGlobalDirServerServer(server, &gRPC.GlobalDirServer{})
	protos.RegisterProcServer(server, &gRPC.ProcsServer{})
	log.Panic("gRPCListener", log.Err(server.Serve(listener)))
}

func httpListener() {
	httpServe := grope.NewHTTPServe()
	router.RouteResource(httpServe)
	router.RouteProc(httpServe)
	router.RouteStack(httpServe)
	router.RouteProject(httpServe)
	router.RouteService(httpServe)
	router.RouteContainer(httpServe)
	router.RouteImage(httpServe)
	router.RouteDir(httpServe)
	proc.RouterProc(httpServe)
	proc.RouterEnhance(httpServe)
	grope.ListenAndServe(":20220", httpServe)
}

func jsonListener() {
	var (
		listener net.Listener
		err      error
	)
	if listener, err = net.Listen("tcp", ":20218"); nil != err {
		panic(err)
	}
	defer func() { _ = listener.Close() }()
	log.Debug("jsonRPCListener", log.Field("jsonrpc", "server start"))
	if err = rpc.Register(&jRPC.System{}); nil != err {
		panic(err)
	}
	if err = rpc.Register(&jRPC.Container{}); nil != err {
		panic(err)
	}
	if err = rpc.Register(&jRPC.Image{}); nil != err {
		panic(err)
	}
	if err = rpc.Register(&jRPC.Network{}); nil != err {
		panic(err)
	}
	if err = rpc.Register(&jRPC.Node{}); nil != err {
		panic(err)
	}
	if err = rpc.Register(&jRPC.Service{}); nil != err {
		panic(err)
	}
	if err = rpc.Register(&jRPC.Swarm{}); nil != err {
		panic(err)
	}
	for {
		conn, err := listener.Accept()
		if nil != err {
			log.Error("Accept", log.Field("jsonrpc", "listener server failed"), log.Err(err))
			continue
		}
		go jsonrpc.ServeConn(conn)
	}
}

func main() {
	if comm.Worker {
		go service.ScheduledStartSend()
		proc.ListenStart("swarm:20219", false)
	}
	go httpListener()
	go gRPCListener()
	jsonListener()
}
